class CategoryController < ApplicationController
  caches_page :show, :all, :categories
  
  def all
    @provinces = Province.find(:all, :order => "name")
    @counties = County.find_all_by_province_id(params[:province], :order => "name") if params[:province]
    @searchqueries = Searchquery.find(:all, :order => "count DESC", :limit => 40)
    @categories = Category.find_by_category_id(0).categories
    @page_title += " - Rättvis näthandel"
  end

  def categories
    @categories = Category.find_by_category_id(0).categories
    render :partial => "/category/categories"
  end

  def show
    @searchqueries = Searchquery.find(:all, :order => "count DESC", :limit => 40)

    if params[:category]
      @category = Category.find_by_id(params[:category])
    elsif !params[:query]
      all
      render :action => :all
      return
    else
      @category = Category.find_by_category_id(0)
    end
    
    @page_title = "Säljes #{@category.unformatted_category_path}"
    if @province
      @page_title += " i "
      if @county
        @page_title += @county.name + ", "
      end
      @page_title += @province.name
    end
    
    #@ads = @category.recursive_ads_desc_end(@province,@county)
    @ads = Ad.search("", params[:category], nil, params[:province], params[:county])
  end

  def subscription
    @category_id = params[:id]
    begin
      @category_subscription = CategorySubscription.find_by_category_id_and_user_id(@category_id,session[:user].id)
    rescue
    end
    render :action => :subscription
  end

  def subscription_form
    category_id = params[:id]
    user_id = session[:user].id
    category_subscription = CategorySubscription.find_by_category_id_and_user_id(category_id,user_id)
    render :partial => "subscription_form", :locals => { :category_id => category_id, :category_subscription => category_subscription }
  end

  def subscription_create
    category_id = params[:id]
    user_id = session[:user].id
    keywords = params[:keywords]
    category_subscription = CategorySubscription.create_subscription(category_id, user_id, keywords)
    render :partial => "subscription", :locals => { :category_id => category_id, :category_subscription => category_subscription }
  end

  def subscription_delete
    category_id = params[:id]
    user_id = session[:user].id
    CategorySubscription.delete_subscription(category_id, user_id)
    render :partial => "subscription", :locals => { :category_id => category_id, :category_subscription => nil }
  end
end
